package com.gk.study.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gk.study.entity.Score;
import com.gk.study.entity.Thing;
import com.gk.study.entity.ThingTag;
import com.gk.study.mapper.ScoreMapper;
import com.gk.study.mapper.ThingMapper;
import com.gk.study.mapper.ThingTagMapper;
import com.gk.study.service.ThingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ThingServiceImpl extends ServiceImpl<ThingMapper, Thing> implements ThingService {
    @Autowired
    ThingMapper mapper;

    @Autowired
    ThingTagMapper thingTagMapper;

    @Autowired
    ScoreMapper scoreMapper;

    @Override
    public List<Thing> getThingList(String keyword, String sort, String c, String tag) {
        QueryWrapper<Thing> queryWrapper = new QueryWrapper<>();

        // 搜索
        queryWrapper.like(StringUtils.isNotBlank(keyword), "title", keyword);

        // 排序
        if (StringUtils.isNotBlank(sort)) {
            if (sort.equals("recent")) {
                queryWrapper.orderBy(true, false, "create_time");
            } else if (sort.equals("hot") || sort.equals("recommend")) {
                queryWrapper.orderBy(true, false, "pv");
            }
        } else {
            queryWrapper.orderBy(true, false, "create_time");
        }

        // 根据分类筛选
        if (StringUtils.isNotBlank(c) && !c.equals("-1")) {
            queryWrapper.eq(true, "classification_id", c);
        }

        List<Thing> things = mapper.selectList(queryWrapper);

        // tag筛选
        if (StringUtils.isNotBlank(tag)) {
            List<Thing> tThings = new ArrayList<>();
            QueryWrapper<ThingTag> thingTagQueryWrapper = new QueryWrapper<>();
            thingTagQueryWrapper.eq("tag_id", tag);
            List<ThingTag> thingTagList = thingTagMapper.selectList(thingTagQueryWrapper);
            for (Thing thing : things) {
                for (ThingTag thingTag : thingTagList) {
                    if (thing.getId().equals(thingTag.getThingId())) {
                        tThings.add(thing);
                    }
                }
            }
            things.clear();
            things.addAll(tThings);
        }

        // 附加tag
        for (Thing thing : things) {
            QueryWrapper<ThingTag> thingTagQueryWrapper = new QueryWrapper<>();
            thingTagQueryWrapper.lambda().eq(ThingTag::getThingId, thing.getId());
            List<ThingTag> thingTags = thingTagMapper.selectList(thingTagQueryWrapper);
            List<Long> tags = thingTags.stream().map(ThingTag::getTagId).collect(Collectors.toList());
            thing.setTags(tags);

            // 计算平均分数
            QueryWrapper<Score> scoreQueryWrapper = new QueryWrapper<>();
            scoreQueryWrapper.eq("teacher_id", thing.getId());
            List<Score> scores = scoreMapper.selectList(scoreQueryWrapper);
            if (!scores.isEmpty()) {
                double totalScore = 0;
                for (Score score : scores) {
                    totalScore += score.getScore();
                }
                double avgScore = totalScore / scores.size();
                thing.setAvgScore(avgScore);
            } else {
                thing.setAvgScore(0.0);
            }
        }
        return things;
    }

    @Override
    public void createThing(Thing thing) {
        System.out.println(thing);
        thing.setCreateTime(String.valueOf(System.currentTimeMillis()));

        if (thing.getPv() == null) {
            thing.setPv("0");
        }
        if (thing.getScore() == null) {
            thing.setScore("0");
        }
        if (thing.getWishCount() == null) {
            thing.setWishCount("0");
        }
        thing.setCourseName(thing.getCourseName()); // 显式设置值
        mapper.insert(thing);
        // 更新tag
        setThingTags(thing);


    }

    @Override
    public void deleteThing(String id) {
        mapper.deleteById(id);
    }

    @Override
    public void updateThing(Thing thing) {

        // 使用MyBatis-Plus的动态字段更新
        UpdateWrapper<Thing> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", thing.getId());

        if (thing.getStatus() != null) {
            updateWrapper.set("status", thing.getStatus());
        }
        if(thing.getTitle() != null) updateWrapper.set("title", thing.getTitle());
        if(thing.getCover() != null) updateWrapper.set("cover", thing.getCover());
        if(thing.getDescription() != null) updateWrapper.set("description", thing.getDescription());
        if(thing.getPrice() != null) updateWrapper.set("price", thing.getPrice());
        if(thing.getMobile() != null) updateWrapper.set("mobile", thing.getMobile());
        if(thing.getAge() != null) updateWrapper.set("age", thing.getAge());
        if(thing.getSex() != null) updateWrapper.set("sex", thing.getSex());
        if(thing.getLocation() != null) updateWrapper.set("location", thing.getLocation());
        if(thing.getCourseName() != null) updateWrapper.set("course_name", thing.getCourseName());
        if (thing.getClassificationId() != null) {
            updateWrapper.set("classification_id", thing.getClassificationId());
        }

        mapper.update(null, updateWrapper);
        setThingTags(thing); // 更新标签


    }

    @Override
    public Thing getThingById(String id) {
        Thing thing = mapper.selectById(id);
        thing.setPv(String.valueOf(Integer.parseInt(thing.getPv()) + 1));
        mapper.updateById(thing);

        // 计算平均分数
        QueryWrapper<Score> scoreQueryWrapper = new QueryWrapper<>();
        scoreQueryWrapper.eq("teacher_id", thing.getId());
        List<Score> scores = scoreMapper.selectList(scoreQueryWrapper);
        if (!scores.isEmpty()) {
            double totalScore = 0;
            for (Score score : scores) {
                totalScore += score.getScore();
            }
            double avgScore = totalScore / scores.size();
            thing.setAvgScore(avgScore);
        } else {
            thing.setAvgScore(0.0);
        }

        return thing;
    }

    // 心愿数加1
    @Override
    public void addWishCount(String thingId) {
        Thing thing = mapper.selectById(thingId);
        thing.setWishCount(String.valueOf(Integer.parseInt(thing.getWishCount()) + 1));
        mapper.updateById(thing);
    }

    // 收藏数加1
    @Override
    public void addCollectCount(String thingId) {
        Thing thing = mapper.selectById(thingId);
        thing.setCollectCount(String.valueOf(Integer.parseInt(thing.getCollectCount()) + 1));
        mapper.updateById(thing);
    }

    @Override
    public List<Thing> getUserThing(String userId) {
        QueryWrapper<Thing> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        return mapper.selectList(queryWrapper);
    }

    public void setThingTags(Thing thing) {
        // 删除tag
        Map<String, Object> map = new HashMap<>();
        map.put("thing_id", thing.getId());
        thingTagMapper.deleteByMap(map);
        // 新增tag
        if (thing.getTags() != null) {
            for (Long tag : thing.getTags()) {
                ThingTag thingTag = new ThingTag();
                thingTag.setThingId(thing.getId());
                thingTag.setTagId(tag);
                thingTagMapper.insert(thingTag);

                // 获取自增id并更新到b_thing表
                Long generatedId = thingTag.getId(); // 需确保MyBatis返回主键
                UpdateWrapper<Thing> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("id", thing.getId())
                        .set("thing_tag_id", generatedId);
                mapper.update(null, updateWrapper);
            }
        }
    }


    @Override
    public Thing getThingByUserId(String userId) {
        QueryWrapper<Thing> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        return mapper.selectOne(queryWrapper);
    }

}
